package scitc.alumni.service.Impl;

import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import scitc.alumni.model.User;
import scitc.alumni.repository.UserRepository;

@Service
public class UserAuthService implements UserDetailsService {

    @Resource
    UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //return null;
        if(username == null || username.isEmpty()){
            return  null;
        }
        // 从数据库读取用户信息
        User user = userRepository.findByUsername(username);
        if(user == null) {
            //throw new Exception("用户不存在");
            return  null;
        }else{
            UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
                    .roles(user.getRole())
                    .username(user.getUsername())
                    .password(user.getPassword())
                    .build();
            return  userDetails;
        }

    }

}
